<!--课程与题库-在线课程-编辑在线课程-->
<template>
  <div class="form-container">
    <el-card class="box-card">
      <div class="card-header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/teachers/teacherEdit'}">在线课程</el-breadcrumb-item>
          <el-breadcrumb-item>添加/编辑在线课程</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form" ref="baseForm" label-width="120px">
        <div class="head-card">
          <!-- 讲师名称 -->
          <el-form-item label="课程名称：" prop="user_name" class="required-item">
            <el-input
              v-model="form.courseName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 专业等级 -->
          <el-form-item label="专业等级：" prop="qyxx_type">
            <el-select
              v-model="form.courseLevel"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in zylevel"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 价格 -->
          <el-form-item label="价格：" prop="user_dev">
            <el-input
              v-model="form.courseSalary"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 讲师 -->
          <el-form-item label="讲师：" prop="qyxx_type">
            <el-select
              v-model="form.courseTeacher"
              placeholder="请选择"
              style="width: 100%"
              multiple
            >
              <el-option
                v-for="item in teacherList"
                :key="item.bt_code"
                :label="item.bt_name"
                :value="item.bt_code">
              </el-option>
            </el-select>
          </el-form-item>

          <!--有效期-->
          <el-form-item label="分佣方式">
            <el-radio-group v-model="form.courseFenyong" @input="chanageRadio">
              <el-radio label="0">购买后
                <el-input v-model="form.courseDay" :disabled="form.courseFenyong !='0'" placeholder="请输入" style="width: 80px"></el-input>天有效
              </el-radio>
              <el-radio label="1">永久有效
<!--                <el-input v-model="form.gudingfy" placeholder="请输入" style="width: 80px"></el-input>元-->
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 退款 -->
          <el-form-item label="退款：" prop="user_dev">
            购买后<el-input
              v-model="form.courseTkTime"
              placeholder="请输入"
              clearable
              style="width: 100px"
            ></el-input>小时内可退
          </el-form-item>

          <!-- 封面 -->
          <el-form-item label="封面：">
            <!--    封面-->
              <div>
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :auto-upload="false"
                  :on-change="changeavart"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="form.courseimgUrl" :src="form.courseimgUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            <div class="upload-tip">展示于列表和详情页。图片小于1M。
              建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
          </el-form-item>

          <!-- 讲师介绍 -->
          <el-form-item label="课程介绍：" prop="user_phoneno" >
            <el-input
              v-model="form.courseDetail"
              placeholder="请输入"
              clearable
              type="textarea"
              rows="10"
            ></el-input>
          </el-form-item>
        </div>
        <!--表单操作 -->
        <el-form-item>
<!--          <el-button type="primary" :disabled="isButtonDisabled" @click="savePublic">保存，编辑课程表</el-button>-->
          <el-button type="primary" @click="saveTeachers">保存</el-button>
          <el-button type="primary" @click="teacherCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {createcb, querybtlist, regjguserfail, updatecb, uploadres} from "../../api/InstitutionApi";

export default {
  data() {
    return {
      form: {
        courseCode:'',
        courseName:'', ///课程名称
        courseLevel:'', ///专业等级
        courseSalary: '', ///价格
        courseTeacher:[], ///讲师
        courseDay: '0', ///购买后几天有效
        courseFenyong: '', ///分佣方式，选择哪个
        courseTkTime: '', ////退款时间
        courseimgUrl:'', ///课程封面
        courseDetail: '', ///课程描述
      },
      type: [
        {
          value: '护理',
          label: '护理'
        }, {
          value: '康养',
          label: '康养'
        },
      ],
      // 图片存储
      imageUrl:'',
      base64Data: null,
      apiImgCode: '',

      logoimgurl:'',
      doorimgurl:'',
      inImgurl: [],
      zizhaoImg: '',
      srcList:[],
      // 弹窗存储
      editFormVisible: false,
      unReview:'',
      // 题库
      zylevel: [
        { value: '1', label: '一级' },
        { value: '2', label: '二级' },
        { value: '3', label: '三级' },
        { value: '4', label: '四级' },
        { value: '5', label: '五级' },
      ],
      // 讲师列表
      teacherList: [],
      addressOptions: [
        {
          value: 'zhejiang',
          label: '浙江省',
          children: [
            {
              value: 'hangzhou',
              label: '杭州市',
              children: [
                { value: 'xihu', label: '西湖区' },
                { value: 'binjiang', label: '滨江区' }
              ]
            }
          ]
        },
        {
          value: 'jiangsu',
          label: '江苏省',
          children: [
            {
              value: 'nanjing',
              label: '南京市',
              children: [
                { value: 'xuanwu', label: '玄武区' },
                { value: 'qinhuai', label: '秦淮区' }
              ]
            }
          ]
        }
      ],
      rowEdit: '', ////传过来的选中项的内容
    }
  },
  created() {
    // 对于 path: '/detail/:flowId' 的匹配
    // this.form = this.$route.query.flowid;
    // this.imgPhoto()
    this.rowEdit = ''
    this.rowEdit = this.$route.query.row;
    if(this.rowEdit) {
      this.editCourse()
    }
    console.log('编辑课程：',this.rowEdit);
  //   调取讲师名字
    this.getTeacher()
  },
  computed: {
    isButtonDisabled() {
      // return this.form.base.cur_status === 2; // 可以扩展其他条件，如 || this.isLoading
    }
  },
  methods: {
    disabled() {
      return disabled
    },
    // 编辑时填写内容
    editCourse() {
      this.form.courseCode = this.rowEdit.bc_code, ///课程code
      this.form.courseName =this.rowEdit.bc_name, ///课程名称
      this.form.courseLevel = this.zylevel.find(item => item.label === String(this.rowEdit.bc_zylevel)).label, ///专业等级
      this.form.courseSalary = this.rowEdit.bc_price, ///价格
      this.form.courseDay = this.rowEdit.bc_effectdays, ///购买后几天有效
      this.form.courseFenyong = String(this.rowEdit.bc_effecttype), ///分佣方式，选择哪个
      this.form.courseTkTime = this.rowEdit.bc_tuikuanhours, ////退款时间
      this.form.courseimgUrl =this.rowEdit.bc_logo_uri[0].url,   ///课程封面
      this.apiImgCode = this.rowEdit.bc_logo_uri[0].imguri,
      this.form.courseDetail = this.rowEdit.bc_desc   ///课程描述
      for(let i=0; i< this.rowEdit.bctinfo.length; i++){
        this.form.courseTeacher.push(this.rowEdit.bctinfo[i].bt_code) ///讲师
      }
    },
    // 调取讲师名字列表
    getTeacher() {
      querybtlist({}).then(res => {
        // this.tableDate = res.data.base_info;
        console.log('讲师列表：', res);
        // this.tableDate = res.data.data.base_info
        this.teacherList = res.data.data.base_info
      })
    },
    // 当选择项变化时
    chanageRadio(lable) {
      console.log('单项变化时：',lable)
      if(lable == 1) {
        this.form.courseDay = '0'
      }
    },
    // 保存并发布
    savePublic() {

    },
    // 保存在线课程
    saveTeachers() {
      if(this.rowEdit) {
       //  编辑
       updatecb({
         "bccode": this.form.courseCode, ///课程code
         "bcname": this.form.courseName, //#课程名称
         "bczylevel": this.form.courseLevel,//#专业等级
         "bcprice": this.form.courseSalary,//#课程价格
         "bceffectdays": this.form.courseDay  ? this.form.courseDay : 0,//#课程有效天数 大于0时有效类型为0
         "bceffecttype": this.form.courseFenyong  ? this.form.courseFenyong : 0,//#课程有效类型，0有效天数，1无限天数（此时有效天数传0）
         "bctlist": this.form.courseTeacher,//#讲师code列表
         "bctuikuanhours": this.form.courseTkTime ? this.form.courseTkTime : 0,//#课程退款时间
         "bclogo_uri": this.apiImgCode,//#课程logo uri
         "bcdesc": this.form.courseDetail,//#课程描述
       }).then(res => {
         console.log('编辑：', res)
         if (res.msg === '更新课程基础信息成功') {
           this.$message({
             type: 'success',
             message: '更新课程基础信息成功!'
           })
           this.$router.push({
             path: '/onlineCourse/index',
             query: ''
           });
         }
       }).catch(err => {
         this.$message.error('课程更新失败，请稍后再试！')
       })
      } else {
        // 添加
        console.log('课程提交：', this.form);
        createcb({
          "bcname": this.form.courseName, //#课程名称
          "bczylevel": this.form.courseLevel,//#专业等级
          "bcprice": this.form.courseSalary,//#课程价格
          "bceffectdays": this.form.courseDay ? this.form.courseDay : 0,//#课程有效天数 大于0时有效类型为0
          "bceffecttype": this.form.courseFenyong ? this.form.courseFenyong : 0,//#课程有效类型，0有效天数，1无限天数（此时有效天数传0）
          "bctlist": this.form.courseTeacher,//#讲师code列表
          "bctuikuanhours": this.form.courseTkTime ? this.form.courseTkTime : 0,//#课程退款时间
          "bclogo_uri": this.apiImgCode,//#课程logo uri
          "bcdesc": this.form.courseDetail,//#课程描述
        }).then(res=> {
          console.log('讲师保存',res)
          this.$router.push({
            path: '/onlineCourse/index',
            query: ''
          });

        })
      }

    },
    // 取消
    teacherCancel() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });

      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/onlineCourse/index',
        query: ''
      });

    },


    //头像
    // 头像上传
    // 自定义上传方法
    customUpload(params) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc":"课程图片"  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.apiImgCode = res.data.base_info
      })

    },

      // 上传前将图片转为base64
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.form.courseimgUrl = reader.result; // 带前缀的完整Base64，可直接用于<img>显示

          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload()
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },




    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //头像结束


    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },


    // 审核不通过
    reviewUnBy(flowid){
      console.log('驳回-1：',flowid);
      regjguserfail({
        "flowid": flowid,
        "flowmsg": this.unReview,
      }).then(res => {
        console.log('驳回：',res,this.unReview);
        this.editFormVisible = false
      })
    },
    resetForm() {
      this.$refs.baseForm.resetFields();
      this.form.businessStatus = '营业中';
      this.form.logoUrl = '';
    },
  }
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
}

.head-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 30px;
}

.card-select {
  padding-left: 40px;
  font-size: 14px;
  margin-bottom: 30px;

}

.form-title {
  font-size: 18px;
  font-weight: bold;
}

.required-item >>> .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
